import { _decorator, Component, Node, director, System, Eventify, log, js, sys } from 'cc';
import { sdk } from '../SDKManager';
const { ccclass, property } = _decorator;

declare const wx;

const title = '消到完全停不下来';
const imageUrlId = 'dxfWFBHQQOye72+o1FQ05g==';
const imageUrl = 'https://mmocgame.qpic.cn/wechatgame/0tfNl6q6IiasOpHNOKTud2f5tAibQ585N98816XxsmM3sI8sTb8XgzIsLnjjwxULic0/0';

@ccclass('WechatManager')
export class WechatManager extends Eventify(System) {

    public static instance: WechatManager;
    static ID = 'wechat_system';
    public codeId;
    isError: boolean = false;
    time: number = 0;

    registerSystem() {
        director.unregisterSystem(director.getSystem(WechatManager.ID));
        director.registerSystem(WechatManager.ID, wcm, System.Priority.MEDIUM);
        wcm.init();
    }

    init() {
        log(`<${js.getClassName(this)}>`, 'init');
        // 打开转发分享
        wx?.showShareMenu?.({
            menus: ['shareAppMessage', 'shareTimeline']
        });
        wx?.onShareAppMessage?.(function () {
            console.log('@onShareAppMessage', arguments);
            sdk.onShareAppMessageCommand.execute(arguments);
            return {
                title: title,
                imageUrlId: imageUrlId,
                imageUrl: imageUrl,
            };
        });
        wx?.onShareTimeline?.(function () {
            console.log('@onShareTimeline', arguments);
            return {};
        });
    }

    loginResolve: (value: boolean) => void = null;

    gameLogin() {
        return new Promise(resolve => {
            this.loginResolve = resolve;
            if (sys.platform == sys.Platform.WECHAT_GAME) {
                console.log(`微信小游戏登录`);
                const self = this;
                globalThis.wx.login({
                    force: true,
                    success(res) {
                        console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
                        this.codeId = res.codeId;
                        // 获取用户授权信息，若没有授权请求用户授权
                        self.WeChatGameSetting();
                    },
                    fail(res) {
                        console.log(`login 调是用失败`);
                    },
                });
            } else {
                resolve(true);
            }
        });
    }


    checkOpenId(APPID, SECRET, CODE, callback) {
        globalThis.wx.request({
            url: `https://api.weixin.qq.com/sns/jscode2session?appid=${APPID}&secret=${SECRET}&js_code=${CODE}&grant_type=authorization_code`,
            success: function (res) {
                console.log('获取用户 openid 成功：' + res.data.openid);
                callback(res.data.openid)
                // TODO: 使用 openid 进行实名认证等操作
            },
            fail: function (res) {
                console.log('获取用户 openid 失败：' + res.errMsg);
            }
        });
    }

    /**
     * 字节跳动平台 登录、授权、请求用户信息、实名认证
     */
    private WeChatGameLogin() {
        console.log(`微信小游戏登录`);
        const self = this;
        globalThis.wx.login({
            force: true,
            success(res) {
                console.log(`login 调用成功${res.code} ${res.anonymousCode}`);
                // 获取用户授权信息，若没有授权请求用户授权
                self.WeChatGameSetting();
            },
            fail(res) {
                console.log(`login 调是用失败`);
            },
        });
    }
    private WeChatGameSetting() {
        console.log(`微信小游戏获取授权信息`);
        const self = this;
        globalThis.wx.getSetting({
            success: (res) => {
                if (res.authSetting['scope.userInfo']) {
                    console.log(`已经获得用户信息授权,请求用户信息 `, res);
                    self.WeChatGameGetUserInfo();
                } else {
                    console.log(`还没有获得用户信息授权，请求用户授权`, res);
                    self.WeChatGameAuthorize();
                }
            }
        });
    }
    private WeChatGameAuthorize() {
        console.log(`微信小游戏获取授权信息`);
        const self = this;
        globalThis.wx.authorize({
            scope: "scope.userInfo",
            success(res) {
                console.log(`用户授权成功`, res);
                self.WeChatGameGetUserInfo();
            },
            fail(res) {
                console.log(`用户授权失败`, res);
                self.loginResolve && self.loginResolve(false);
            },
        })
    }
    private WeChatGameGetUserInfo() {
        console.log(`微信小游戏获取用户信息信息`);
        let self = this;
        globalThis.wx.getUserInfo({
            // withCredentials: true,
            withRealNameAuthenticationInfo: true,
            success(res) {
                let info = res.userInfo;
                console.log('info:', info);
                if (res.realNameAuthenticationStatus == "certified") {
                    console.log(`已实名认证`);
                    self.loginResolve && self.loginResolve(true);
                } else {
                    console.log(`未实名认证`);
                    self.loginResolve && self.loginResolve(true);
                    //todo 实名认证,需要服务器支持,往后放
                    //self.WeChatGameRealName();
                }
            },
            fail(res) {
                console.log(`getUserInfo 调用失败`, res.errMsg);
            },
        });
    }
    private WeChatGameRealName() {
        let self = this;
    }

    report(eventName: string, data: Record<string, string | number>) {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            // let eventNameWX = `expt_${eventName}`;
            let eventNameWX = `${eventName}`;
            console.log('report', eventNameWX, data);
            globalThis.wx.reportEvent(eventNameWX, data);
        }
    }

    share() {
        if (sys.platform == sys.Platform.WECHAT_GAME) {
            console.log('@wcm share');
            globalThis.wx?.updateShareMenu({
                withShareTicket: true,
                success() { console.log('@share success', arguments) },
                fail() { console.log('@share fail', arguments) }
            })
        }
    }

    vibrateShort() {
        if (globalThis.wx?.vibrateShort) {
            globalThis.wx?.vibrateShort({
                success() { },
                fail() { }
            });

        }
    }

    vibrateLong() {
        if (globalThis.wx?.vibrateLong) {
            globalThis.wx?.vibrateLong({
                success() { },
                fail() { }
            });
        }
    }

    shareAppMessage() {
        if (globalThis.wx?.shareAppMessage) {
            globalThis.wx.shareAppMessage({
                title: title,
                imageUrlId: imageUrlId,
                imageUrl: imageUrl,
            });
            setTimeout(() => {
                sdk.onShareAppMessageCommand.execute(arguments);
            }, 1000);
        }
    }
}

globalThis.WechatManager = WechatManager;

export const wcm = WechatManager.instance = new WechatManager();